package dao

import (
	"gorm.io/gorm"
	"my-blog/main/entity"
	"strconv"
)

// GetArticleClassAndShortArticleList 入参 db 第几页 返回结果和总数
func GetArticleClassAndShortArticleList(db *gorm.DB, p string, classId int) ([]entity.ArticleClass, int64, int, []entity.Article) {
	var page int
	if p == "" {
		page = 1
	} else {
		page, _ = strconv.Atoi(p)
	}
	if page < 1 {
		page = 1
	}
	var articleClass []entity.ArticleClass
	var count int64

	// 文章分类
	db.Where(entity.Article{Status: 1}).Find(&articleClass)

	// 查询总数
	db.Model(entity.Article{}).Where(&entity.Article{Status: 1, ClassId: classId}).Count(&count)
	var start = (page - 1) * 7
	if int(count) < start {
		start = int(count) - int(count)%7
	}

	var shortArticleList []entity.Article
	if count > 0 {
		db.Where(entity.Article{ClassId: classId, Status: 1}).Limit(7).Offset(start).Find(&shortArticleList)
	}
	var currentPage = start/7 + 1
	return articleClass, count, currentPage, shortArticleList
}

func GetArticleDetails(db *gorm.DB, id int) (entity.Article, string) {
	var article entity.Article
	db.Where(entity.Article{Id: id, Status: 1}).Find(&article)
	var articleClass entity.ArticleClass
	db.Where(entity.ArticleClass{Id: article.ClassId}).Find(&articleClass)
	return article, articleClass.Name
}
